package com.kevin.j2eeToolBox.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailTest extends Authenticator {

	private String d_email = "zwy1124@gmail.com";
	private String d_uname = "email";
	private String d_password = "yan851005";
	private String d_host = "smtp.gmail.com";
	private String d_port = "465"; // 465,587
	private String m_to = "zwy1124@gmail.com";
	private String m_subject = "Testing";
	private String m_text = "Hey, this is the testing email.";

	public PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(d_email, d_password);
	}

	/**
	 * @param args
	 * @throws MessagingException
	 */
	public static void main(String[] args) throws MessagingException {

		MailTest test = new MailTest();
		test.sendMail();

	}

	private void sendMail() throws NoSuchProviderException, MessagingException,
			AddressException {
		// TODO Auto-generated method stub
		// String mailhost = "smtp.gmail.com";
		boolean debug = true;

		// Properties props = System.getProperties();
		// props.put("mail.smtp.host", mailhost);

		Properties props = new Properties();
		props.put("mail.smtp.user", d_email);
		props.put("mail.smtp.host", d_host);
		props.put("mail.smtp.port", d_port);
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.debug", "true");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.socketFactory.port", d_port);
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.socketFactory.fallback", "false");

		// Authenticator authenticator = Se

		Authenticator auth = new MailTest();

		Session session = Session.getDefaultInstance(props, auth);
		if (debug)
			session.setDebug(debug);

		Message msg = new MimeMessage(session);
		msg.setText(m_text);
		msg.setSubject(m_subject);
		msg.setFrom(new InternetAddress(d_email));
		msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to));
		Transport transport = session.getTransport("smtps");
		transport.connect(d_host, 465, d_uname, d_password);
		transport.sendMessage(msg, msg.getAllRecipients());
		transport.close();
	}
}
